package com.zlt.service.impl;

import com.alipay.api.domain.ChatMessage;
import com.zlt.dao.ChatMessageDao;
import com.zlt.dao.DeliveryDao;
import com.zlt.dao.Impl.ChatMessageDaoImpl;
import com.zlt.dao.Impl.DeliveryDaoImpl;
import com.zlt.dao.Impl.JobDaoImpl;
import com.zlt.dao.JobDao;
import com.zlt.dto.JobDTO;
import com.zlt.entity.*;
import com.zlt.service.JobService;
import com.zlt.util.ActiveUserUtil;
import com.zlt.util.StringUtil;
import com.zlt.vo.*;
import org.apache.commons.beanutils.BeanUtils;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JobServiceImpl implements JobService {

    private DeliveryDao deliveryDao = new DeliveryDaoImpl();

    private JobDao jobDao = new JobDaoImpl();

    private ChatMessageDao chatMessageDao = new ChatMessageDaoImpl();


    @Override
    public List<JobType> selectAllType(int parentId) {
        return jobDao.selectAllType(parentId);
    }

    @Override
    public List<JobType> selectAllTypes(int parseInt) {
        return jobDao.selectAllTypes(parseInt);
    }

    @Override
    public boolean insertJob(JobDTO jobDTO) throws InvocationTargetException, IllegalAccessException {
        //通过uid获取company
        ActiveUser activeUser = ActiveUserUtil.get();
        Company company = jobDao.selectCidByUid(activeUser.getUid(), 0);
        Job job = new Job();
        BeanUtils.copyProperties(job, jobDTO);
        //通过jtid查找job_type
        JobType jobType = jobDao.selectJobTypeByJid(jobDTO.getJtId());
        job.setCompany(company);
        job.setJobType(jobType);
        User user = new User();
        BeanUtils.copyProperties(user, activeUser);
        job.setUser(user);
        return jobDao.insertJob(job);
    }

    public boolean changeCollection(int jid, int state) {

        ActiveUser activeUser = ActiveUserUtil.get();
        System.out.println(activeUser.toString());
        if (activeUser == null) {
            throw new RuntimeException("当前未登录，无法查询");
        }
        String uid = activeUser.getUid();
//        String uid="1";
        //查看当前岗位是否被收藏过
        int result = 0;
        Long num = jobDao.selectCollection(uid, jid);

        if (num == 0) {//没有记录
            result = jobDao.insertCollection(uid, jid, 0);
            //插入成功与否
        } else {//有记录，根据添加或取消需求修改，0为添加收藏，1为取消收藏
            result = jobDao.updateCollection(uid, jid, state);
            //修改成功与否
        }
        return result > 0;
    }

    @Override
    public Map<String, Object> checkOne(int jid) {

        ActiveUser activeUser = ActiveUserUtil.get();
        Integer state = null;
        if (activeUser != null) {
            //岗位收藏状态 0收藏，1/null 未收藏 -----有在线用户才查
            state = jobDao.collectionState(activeUser.getUid(), jid);
        }
        JobVo jobVo = new JobVo();
        CompanyVO companyVO = new CompanyVO();
        UserVo userVo = new UserVo();
        //查出当前岗位信息
        Job job = jobDao.selectOne(jid);

        //查询出当前岗位的招聘者
        String uid = job.getUser().getUid();
        User user = jobDao.selectRecruiter(uid);//查出姓名和头像

        //岗位当前收藏人数
        Long num = jobDao.collectionCount(job.getCompany().getCid());

        //查询岗位所属企业信息
        Company company = jobDao.selectCompany(job.getCompany().getCid());
        try {
            BeanUtils.copyProperties(jobVo, job);
//            BeanUtils.copyProperties(companyVO,company);
//            BeanUtils.copyProperties(userVo,user);
            jobVo.setCollectors(num);
            jobVo.setCollectState(state);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        Map<String, Object> job1 = new HashMap<>();
        job1.put("jobVo", jobVo);
        job1.put("company", company);
        job1.put("recruiter", user);

        return job1;
    }

    @Override
    public Pager<JobVo> checkCollection(Pager<JobVo> pager) {
        ActiveUser activeUser = ActiveUserUtil.get();
        if (activeUser == null) {
            throw new RuntimeException("当前未登录，无法查询");
        }
        List<JobVo> jobVos = new ArrayList<>();
        //岗位总数
        Long totalCount = jobDao.collectTotalCount(activeUser.getUid());
        pager.setTotalCount(totalCount);
        //总页数
        pager.setPageCount(pager.getTotalCount() - 1 / pager.getLimit() + 1);
        //查找出对应位置的job
        List<Map<String, Object>> jobs = jobDao.allCollectionJob(pager,activeUser.getUid());

        //将map转成jobvo
        for (Map<String, Object> m : jobs) {
            JobVo jobVo = new JobVo();
            jobVo.setJid(Integer.parseInt(m.get("jid") + ""));
            jobVo.setJname(m.get("jname") + "");//j.jname,j.min_salary,j.max_salary,j.work_address,t.name,c.cname
//            jobVo.setMinSalary((Double) m.get("min_salary"));
//            jobVo.setMaxSalary((Double) m.get("max_salary"));
//            jobVo.setWorkAddress(m.get("work_address")+"");
            jobVo.setMinSalary(Double.parseDouble(m.get("min_salary") + ""));
            jobVo.setMaxSalary(Double.parseDouble(m.get("max_salary") + ""));
            jobVo.setWorkAddress(m.get("work_address") + "");
            jobVo.setType(m.get("name") + "");
            jobVo.setCname(m.get("cname") + "");
            jobVos.add(jobVo);
        }
        pager.setData(jobVos);
        return pager;
//        //查询收藏岗位的总条数
//        Long totalCount = jobDao.collectTotalCount(activeUser.getUid());//activeUser.getUid()
//        pager.setTotalCount(totalCount);
//        //总页数
//        pager.setPageCount(pager.getTotalCount() - 1 / pager.getLimit() + 1);
//        //查找当前收藏的所有岗位
//        List<Job> jobs = jobDao.allCollectionJob(pager, activeUser.getUid());
//        List<JobVo> jobVos = new ArrayList<>();
//        jobs.forEach(j -> {
//            JobVo jobVo = new JobVo();
//            jobVos.add(jobVo);
//            try {
//                BeanUtils.copyProperties(jobVo, j);
//            } catch (IllegalAccessException e) {
//                e.printStackTrace();
//            } catch (InvocationTargetException e) {
//                e.printStackTrace();
//            }
//        });
//        pager.setData(jobVos);
//        return pager;
    }

    @Override
    public boolean downJob(Integer jid, Integer state) {
        return jobDao.updateJobState(jid, state);
    }

    @Override
    public boolean updateJobInfo(JobDTO jobDTO) {
        return jobDao.updateJobInfo(jobDTO);
    }

    @Override
    public JobVo selectOneJobByJid(Integer jid) {
        Job job = jobDao.selectOneJobByJid(jid);
        JobVo jobVo = new JobVo();
        if (job != null) {
            try {
                BeanUtils.copyProperties(jobVo, job);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }

        return jobVo;
    }

    @Override
    public Pager<JobVo> selectAllJob(Pager<JobVo> pager, String uid) {
        //查询总招聘数量
        Long count = jobDao.selectCountJob();
        if (count != null) {
            pager.setTotalCount(count);
            //总页数
            pager.setPageCount((count - 1) / pager.getLimit() + 1);
            List<Job> jobList = jobDao.selectAllJob(pager, uid);
            List<JobVo> jobVos = new ArrayList<>();
            for (Job job : jobList) {
                JobVo jobVo = new JobVo();
                try {
                    BeanUtils.copyProperties(jobVo, job);

                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
                jobVos.add(jobVo);
            }
            pager.setData(jobVos);
            return pager;
        }
        return null;
    }

    @Override
    public Pager<JobVo> defaultJob(Pager<JobVo> pager) {
        List<JobVo> jobVos = new ArrayList<>();
        //岗位总数
        Long totalCount = jobDao.defaultTotalCount();
        pager.setTotalCount(totalCount);
        //总页数
        pager.setPageCount(pager.getTotalCount() - 1 / pager.getLimit() + 1);
        //查找出对应位置的job
        List<Map<String, Object>> jobs = jobDao.defaultAllJob(pager);

        //将map转成jobvo
        for (Map<String, Object> m : jobs) {
            JobVo jobVo = new JobVo();
            jobVo.setJid(Integer.parseInt(m.get("jid") + ""));
            jobVo.setJname(m.get("jname") + "");//j.jname,j.min_salary,j.max_salary,j.work_address,t.name,c.cname
//            jobVo.setMinSalary((Double) m.get("min_salary"));
//            jobVo.setMaxSalary((Double) m.get("max_salary"));
//            jobVo.setWorkAddress(m.get("work_address")+"");
            jobVo.setMinSalary(Double.parseDouble(m.get("min_salary") + ""));
            jobVo.setMaxSalary(Double.parseDouble(m.get("max_salary") + ""));
            jobVo.setWorkAddress(m.get("work_address") + "");
            jobVo.setType(m.get("name") + "");
            jobVo.setCname(m.get("cname") + "");
            jobVos.add(jobVo);
        }
        pager.setData(jobVos);
        return pager;
    }

    @Override
    public Pager<JobVo> searchJob(Pager<JobVo> pager, JobDTO jobDTO) {
        List params = new ArrayList();
        // 动态sql 根据条件去生成sql
        StringBuilder sql = new StringBuilder();
        sql.append("select j.jid,j.jname,j.work_address,j.min_salary,j.max_salary,jt.name,c.cname from job j left join job_type  jt on j.jtid=jt.jtid left join company c " +
                "on j.cid = c.cid");
        StringBuilder countSql = new StringBuilder();
        countSql.append("select count(*) c from job j");
        StringBuilder whereSql = new StringBuilder();
//        whereSql.append(" where cid=? ");
        whereSql.append(" where 1=1 ");
        if (StringUtil.isNotNull(jobDTO.getJname())) {
            whereSql.append(" and jname like ? ");
            params.add("%" + jobDTO.getJname() + "%");
        }
        if (StringUtil.isNotNull(jobDTO.getWorkAddress())) {
            whereSql.append(" and work_address like ? ");
            params.add("%" + jobDTO.getWorkAddress() + "%");
        }
        if (jobDTO.getJtId() != null && jobDTO.getJtId() != 0) {
            whereSql.append(" and j.jtid=? ");
            params.add(jobDTO.getJtId());
        }
        if (jobDTO.getMinSalary() != null && jobDTO.getMinSalary() != 0) {
            whereSql.append(" and min_salary >=? ");
            params.add(jobDTO.getMinSalary());
        }
        if (jobDTO.getMaxSalary() != null && jobDTO.getMaxSalary() != 0) {
            whereSql.append(" and max_salary <=? ");
            params.add(jobDTO.getMaxSalary());
        }
        sql.append(whereSql);
        countSql.append(whereSql);
        sql.append("limit ?,?");
        System.out.println(sql);
        System.out.println(countSql);
        //先查询总条数
        Long count = jobDao.selectJobCount(countSql, params);
        pager.setTotalCount(count);
        //查询当前页岗位
        List<Job> jobs = jobDao.selectJob(sql, params, pager);
        List<JobVo> jobVOList = new ArrayList<>();
        jobs.forEach(j -> {
            JobVo jobVO = new JobVo();

            jobVOList.add(jobVO);
            jobVO.setCname(j.getCompany().getCname());
            jobVO.setType(j.getJobType().getJtname());
            try {
                BeanUtils.copyProperties(jobVO, j);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        });
        pager.setData(jobVOList);
        return pager;
    }

    @Override
    public List<JobType> selectJobTypeByCid() {
        System.out.println("进入了 select");
        ActiveUser activeUser = ActiveUserUtil.get();
//   获取当前HR 关联的企业id
        Company company = deliveryDao.selectCompanyByUid(activeUser.getUid());
        System.out.println(company);

        List<Job> jobs = jobDao.selectJobByCid(company.getCid());

        List<JobType> jobTypes = new ArrayList<>();
        for (int i = 0; i < jobs.size(); i++) {
            JobType jobType = jobDao.selectJobTypeByJtid(jobs.get(i).getJobType().getJtid());
            jobTypes.add(jobType);
        }
        System.out.println(jobTypes);
        return jobTypes;
    }

    @Override
    public boolean addTalk(String hrId, String cid, String jid) {
        ActiveUser activeUser = ActiveUserUtil.get();
        if (activeUser==null){
            new RuntimeException("未登录");
        }
        String uid = activeUser.getUid();
        ChatMessageMain exist = chatMessageDao.isExist(uid, hrId);
        if (exist == null){
            ChatMessageMain chatMessageMain = new ChatMessageMain();
            chatMessageMain.setJobSeeker(uid);
            chatMessageMain.setRecruiters(hrId);
            chatMessageMain.setSeekerDeleteStatus(Integer.parseInt(jid));
            chatMessageMain.setRecruitersDeleteStatus(Integer.parseInt(cid));
            int result = chatMessageDao.insertMainByClass(chatMessageMain);
            return result > 0;
        }
        return true;
    }
}







